import {useCallback, useEffect, useState} from "react";
import {useStompClient} from "./stomp-service";
import {ChatMessageSendDTO} from "@/types/stomp";
import {SignalMessageRequest} from "@/types/webrtc";

// 聊天消息发送频道
const CHAT_MESSAGE_DESTINATION = "/app/chat";
// WebRTC 信令消息发送频道
const WEBRTC_SIGNAL_DESTINATION = "/app/signal";
// 最大重试次数
const MAX_RETRY_COUNT = 3;

export type StompSendProps = {
    onBeforeSend?: () => void;
    onSendSuccess?: () => void;
    onSendError?: (error: any) => void;
    onRetry?: (retryCount: number) => void;
}

export function useStompSend({
                                 onBeforeSend,
                                 onSendSuccess,
                                 onSendError,
                                 onRetry,
                             }: StompSendProps = {}) {
    const { client, connected } = useStompClient();
    const [messageQueue, setMessageQueue] = useState<{ sendChannel: string ;message: any; retryCount: number }[]>([]);

    const sendChatMessage = useCallback(
        (message: ChatMessageSendDTO<any, any>) => {
            if (!connected || !client) {
                onSendError && onSendError(new Error("STOMP 客户端未连接"));
                console.error("STOMP 客户端未连接，消息加入队列");
                setMessageQueue((prevQueue) => [
                    ...prevQueue,
                    {
                        sendChannel: CHAT_MESSAGE_DESTINATION,
                        message,
                        retryCount: 0
                    },
                ]);
                return;
            }

            try {
                onBeforeSend && onBeforeSend();
                client.publish({
                    destination: CHAT_MESSAGE_DESTINATION,
                    body: JSON.stringify(message),
                });
                onSendSuccess && onSendSuccess();
                console.log("消息已发送:", message);
            } catch (error) {
                onSendError && onSendError(error);
                console.error("发送消息时出错，消息加入队列:", error);
                setMessageQueue((prevQueue) => [
                    ...prevQueue,
                    {
                        sendChannel: CHAT_MESSAGE_DESTINATION,
                        message,
                        retryCount: 0
                    },
                ]);
            }
        },
        [client, connected]
    );

    const sendRTCMessage = useCallback(
        (message: SignalMessageRequest)  => {
            if (!connected || !client) {
                onSendError && onSendError(new Error("STOMP 客户端未连接"));
                console.error("STOMP 客户端未连接，消息加入队列");
                setMessageQueue((prevQueue) => [
                    ...prevQueue,
                    {
                        sendChannel: WEBRTC_SIGNAL_DESTINATION,
                        message,
                        retryCount: 0
                    },
                ]);
                return;
            }

            try {
                onBeforeSend && onBeforeSend();
                client.publish({
                    destination: WEBRTC_SIGNAL_DESTINATION,
                    body: JSON.stringify(message),
                });
                onSendSuccess && onSendSuccess();
                console.log("消息已发送:", message);
            } catch (error) {
                onSendError && onSendError(error);
                console.error("发送消息时出错，消息加入队列:", error);
                setMessageQueue((prevQueue) => [
                    ...prevQueue,
                    {
                        sendChannel: WEBRTC_SIGNAL_DESTINATION,
                        message,
                        retryCount: 0
                    },
                ]);
            }
        },
        [client, connected]
    );



    useEffect(() => {
        if (connected && client && messageQueue.length > 0) {
            setMessageQueue((prevQueue) => {
                const newQueue = [...prevQueue];
                const toRetry = newQueue.shift();

                if (toRetry) {
                    const { sendChannel , message, retryCount } = toRetry;

                    if (retryCount < MAX_RETRY_COUNT) {
                        onRetry && onRetry(retryCount);
                        try {
                            onBeforeSend && onBeforeSend();
                            client.publish({
                                destination: sendChannel,
                                body: JSON.stringify(message),
                            });
                            onSendSuccess && onSendSuccess();
                            console.log("重试发送成功:", message);
                        } catch (error) {
                            onSendError && onSendError(error);
                            console.error("重试发送失败:", error);
                            newQueue.push({
                                sendChannel,
                                message,
                                retryCount: 0
                            },);
                        }
                    } else {
                        onSendError && onSendError(new Error("达到最大重试次数"));
                        console.error("达到最大重试次数，放弃发送:", message);
                    }
                }

                return newQueue;
            });
        }
    }, [connected, client, messageQueue]);

    return { sendChatMessage, sendRTCMessage };
}